<?php
namespace app\ausagent\controller;
use app\ausagent\controller\Common;
use think\Request;
use think\Db;
use think\Session;
use think\Config;
use Godok\Org\Auth;
use Memcached;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\MemcachedCache;
use EasyWeChat\Payment\Order;
class Orders extends Common
{
    private function initialize()
    {
        $gzh = Db::name('wechat_mp')->where('oid',session('oid'))->cache(true)->find();
        $wxpay = Db::name('wechatpay')->where('oid',session('oid'))->cache(true)->find();
        //判断是否为子商户
        $options = [
            'app_id' => config('wechat.APPID'),
            'secret'  =>config('wechat.APPSECRET'),
            'payment' => [
                'merchant_id'        => config('wechat.MCHID'),
                'key'                => config('wechat.KEY'),
                'cert_path'          => config('wechat.SSLCERT_PATH'),
                'key_path'           => config('wechat.SSLKEY_PATH'),
                'notify_url'         => config('website').'/ausagent/Order/rechargenotify',
                'sub_app_id'      => $gzh['appid'],
                'sub_merchant_id' => $wxpay['mchid'],
            ],
            'log' => [
                'level' => 'debug',
                'file'  => '../log/easywechat.log',
            ],
        ];
        if(config('wechatchche')){
            $memcached = new Memcached();
            $memcached->addServer(config('wechatchche.host'), config('wechatchche.port'));
            $cacheDriver = new MemcachedCache();
            $cacheDriver->setMemcached($memcached);
            $options['cache']=$cacheDriver;
        }
        $app = new Application($options);
        return $app;
    }
    //查询充值订单	
    public function index(){
        $b = 'user';//定义用户表	
        $where ='a.is_delete = 1 AND a.pay_status = 1 AND  a.oid = '.session('oid');//.Session::get('oid')获取
        $pages= 20;//每页显示记录数
        $pageParam    = ['query' =>[]];
        if(input('order_no')!=''){
            $where .= ' AND a.order_no = '.input('order_no');
            $pageParam['query']['order_no'] = input('order_no');
            $this->assign('order_no',input('order_no'));
        }
        //获取是否查询到用户名
        if(input('name')!=''){
            $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $pageParam['query']['name'] = input('name');
            $this->assign('name',input('name'));
        }

        //以下代码是判断是否是按支付状态查询

        $list=Db::name('rechargeorder')
            ->alias('a')
            ->join("$b b",'a.oid = b.oid and a.uid = b.id')
            ->field('a.id,a.order_no,a.trade_no,a.balance,a.deposit,a.refunddeposit,a.pay_mode,a.pay_status,a.payment_date,a.create_time,a.is_delete,b.name')
            ->where($where)
            ->order('a.create_time DESC')
            ->paginate($pages, false, $pageParam);

        $this->assign('list',$list);

        return $this->fetch('../application/publicview/orders/index.html');
    }

    //租还记录
    public function leaseorder(){
        $u = 'user';//定义用户表
        $s = 'seller';//定义商家表
        $pages = 20;//定义默认显示每页显示记录数
        $pageParam    = ['query' =>[]];
        $where = 'a.is_delete = 1 AND a.oid = '.session('oid');
        //判断是否有查询订单好
        if(!empty(input('order_no'))){
            $where .= ' AND a.order_no = '.input('order_no');
            $pageParam['query']['order_no'] = input('order_no');
            $this->assign('order_no',input('order_no'));
        }
        //判断是否有查询指定用户名
        if(!empty(input('name'))){

            $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $pageParam['query']['name'] = input('name');
            $this->assign('name',input('name'));
        }
        //判断是否有查询商户名称
        if(!empty(input('sname'))){
            $where .= ' AND c.name LIKE '."'%".input('sname')."%' ";
            $pageParam['query']['sname'] = input('sname');
            $this->assign('sname',input('sname'));
        }
        //判断是否有选择按订单状态
        if(!empty(input('status'))){
            $where .= ' AND a.status = '.input('status');
            $pageParam['query']['status'] = input('status');
        }
        $list=Db::name('leaseorder')
            ->alias('a')
            ->join("$u b",'a.uid = b.id and a.uid = b.id','LEFT')
            ->join("$s c",'a.sid = c.id  and a.oid = c.oid','LEFT')
            ->field('a.id,a.order_no,a.name as lname,a.starttime,a.endtime,a.amount,a.status,a.billingunit,a.payable_amount,a.cabinetid,a.deviceid,a.create_time,b.name,b.picture,a.uid,a.sid,c.name as sname')
            ->where($where)
            ->order('a.starttime DESC')
            ->paginate($pages,false,$pageParam);
        //echo Db::name('leaseorder')->getlastsql();
        //var_dump($list); die;
        $this->assign('list',$list);

        return $this->fetch('../application/publicview/orders/leaseorder.html');
    }

    //租还记录有些信息手动修改
    public function leaseorderedit($id='', $data= ''){

        $id = Request::instance()->get('id','','number_int');
        $u = 'user';//定义用户表
        $s = 'seller';//定义商家表
        $where = 'a.id = '.$id;
        $list=Db::name('leaseorder')
            ->alias('a')
            ->join("$u b",'a.oid = b.oid and a.uid = b.id','LEFT')
            ->join("$s c",'a.sid = c.id and a.oid = c.oid','LEFT')
            ->field('a.id,a.oid,a.order_no,a.name as lname,a.starttime,a.endtime,a.amount,a.status,a.billingunit,a.payable_amount,a.cabinetid,a.deviceid,a.create_time,a.remarks,b.name,b.picture,a.uid,a.sid,c.name as sname')
            ->where($where)
            ->find();
        //var_dump($list); die;	
        //
        if ( Request::instance()->isPost() ) {
            $id = input('id');
            $endtime= strtotime(input('endtime'));
            $remarks = input('remarks');
            $status = input('status');
            if($endtime != $list['endtime'] AND $status != $list['status']){
                $oid = $list['oid'];
                $uid = $list['uid'];
                //获取运营商价格
                $operator = Db::name('operator')
                    ->where('id',$oid)
                    ->cache(true)
                    ->find();
                if ($operator['billingunit'] == 1) {
                    $arithmetical = 3600;
                } else {
                    $arithmetical = 60;
                }

                $time = $endtime;

                $billingunit =  ceil(($time - $list['starttime'])/($arithmetical * $operator['billingtime']));    //计费单位       
                $amount = $billingunit * $operator['amount'];//金额
                $data = array(
                    'id' => $id,
                    'endtime' => $time,
                    'billingunit' => $billingunit,
                    'amount' => $amount,
                    'status' => $status,
                    'payable_amount' => $amount,
                    'remarks' =>$remarks,
                    'real_amount' => $amount,

                );
                if(Db::name( 'leaseorder')->update($data)){
                    Db::name('user')->where('oid',$oid)->where('id',$uid)->setDec('balance', $amount);
                    $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="leaseorderedit"; $uid=session('id'); $querystring = '修改'.input('id').'租还订单信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    $this->redirect('index');
                    //return ['code'=>0, 'msg'=>'删除成功！'];
                }else{
                    //return ['code'=>-1050, 'msg'=>'删除失败！'];
                    $this->error('修改失败！');
                }

            }else if($remarks!=$list['remarks']){
                $data['id'] = input('id');
                $data['remarks'] = $remarks;
                if(Db::name( 'leaseorder')->update($data)){
                    $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="leaseorderedit"; $uid=session('id'); $querystring = '修改'.input('id').'租还订单备注信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    $this->redirect('index');
                    //return ['code'=>0, 'msg'=>'删除成功！'];
                }else{
                    //return ['code'=>-1050, 'msg'=>'删除失败！'];
                    $this->error('修改失败！');
                }
            }
        }
        $this->assign('list',$list);

        return $this->fetch('../application/publicview/orders/leaseorderedit.html');
    }

    //押金退款记录
    public function refund(){
        $pages = 20;
        $where = 'a.is_delete = 1 AND a.oid = '.session('oid');
        $pageParam    = ['query' =>[]];
        if(!empty(input('order_no'))){
            $where .= ' AND a.order_no = '.input('order_no');
            $pageParam['query']['order_no'] = input('order_no');
            $this->assign('order_no',input('order_no'))	;
        }
        if(input('name')!=''){
            $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $pageParam['query']['name'] = input('name');
            $this->assign('name',input('name'));
        }
        $b = 'user';
        $c = 'rechargeorder';//充值记录表
        $list=Db::name('refund')
            ->alias('a')
            ->join("$b b",'a.uid = b.id')
            ->join("$c c",'a.order_no = c.order_no')
            ->field('a.id,a.order_no,a.refund_no,a.transaction_id,a.types,a.refund_time,b.mobile,b.name,b.picture,c.deposit,c.refundbalance,c.refunddeposit')
            ->where($where)
            ->order('a.refund_time desc')
            ->paginate($pages,false, $pageParam);
        $this->assign('list',$list);
        return $this->fetch('../application/publicview/orders/refund.html');
    }

    //手动退款
    public function manual(){

        return $this->fetch();
    }

    public function endorder(){
        $id = (int)input('id');
        if ( Request::instance()->isPost() ) {
            //不扣费租借订单处理
            $id = (int)input('id');
            if(!empty($id)){
                $data['status'] = 2;
                $data['endtime'] = time();
                $data['id'] = $id;
                $data['remarks'] = '不扣费订单异常处理';
                $set = Db::name('leaseorder')->update($data);
                if($set){
                    $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="endorder"; $uid=session('id'); $querystring = '结束订单'.$id;$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    return  ['code'=>0, 'msg'=>'结束订单成功!'];
                }else{
                    return ['code'=>-1050, 'msg'=>'结束订单失败！'];
                }
                //var_dump($data);die;
            }else{
                die('非法操作!');
            }
        }else{
            //扣费租借订单页面模版
            $id = Request::instance()->get('id','','number_int');
            if(!empty($id)){
                $this->assign('id',$id);
                $ret = Db::name('leaseorder')->where('id',$id)->find();
                $this->assign('v',$ret);
                return view('../application/publicview/orders/endorder.html');
            }else{
                die('非法操作!');
            }
        }
    }
    public function endorder2(){
        //扣费租借订单处理
        if ( Request::instance()->isPost() ) {
            $id = (int)input('id');
            if(!empty($id)){
                $data = input('post.');
                $oid = (int)input('oid');
                $operator = Db::name('operator')
                    ->where('id',$oid)
                    ->find();
                if($operator){
                    if ($operator['billingunit'] == 1) {
                        $arithmetical = 3600;
                    } else {
                        $arithmetical = 60;
                    }
                    $time = strtotime(input('endtime'));
                    $billingunit =  ceil(($time - $data['starttime'])/($arithmetical * $operator['billingtime']));
                    $amount = $billingunit * $operator['amount'];//金额
                    $data['billingunit'] = $billingunit;//billingtime  billingunit
                    $data['amount'] = $amount;
                    $data['status'] = 2;
                    $data['payable_amount'] = $amount;
                    $data['real_amount'] = $amount;
                    $data['endtime'] = strtotime(input('endtime'));
                    $ret =Db::name('leaseorder')->update($data);
                    if($ret !== false){
                        $fuid = Db::name('leaseorder')->where('id',$data['id'])->find();
                        $find = Db::name('user')->where('id',$fuid['uid'])->find();
                        if(!$find){
                            return ['code'=>-1050, 'msg'=>'没有找到该用户!'];
                        }
                        $balance = $find['balance'] - $amount;
                        $money['balance'] = $balance;
                        $user = Db::name('user')
                            ->where('id',$fuid['uid'])
                            ->update($money);
                        $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="endorder2"; $uid=session('id'); $querystring = '结束用户'.$find['name'].'订单'.$fuid['order_no'];$ip = get_ip();$os = get_os();
                        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                        return ['code'=>0, 'msg'=>'结束订单成功！'];
                    }else{
                        return ['code'=>-1050, 'msg'=>'结束订单失败！'];
                    }
                }else{
                    return ['code'=>-1050, 'msg'=>'获取不到运营商信息,请检查数据表是否对应'];
                }

            }else{
                die('非法操作!');
            }
        }
    }
    //退款租借订单金额
    public function refunds($id=''){


        if ( Request::instance()->isPost() ) {
            $id = (int)input('id');//var_dump($id);
            //$res = Db::name('leaseorder')->where('id',$id)->find();var_dump($res);die;
            $jine = Db::name('rechargeorder')->where(['oid'=>session('oid'),'id'=>$id])->order('create_time desc')->find();
            //var_dump($jine);die;
            $app = $this ->initialize();
            $payment = $app->payment;
            $refundNo = '401' . date('ymdHis') . rand(1000, 9999);
            $real_amount = round($jine['real_amount'],2)*100;
            $reamout = round(input('amount'),2)*100;
            $orderNo = $jine['order_no'];

            # 1. 使用商户订单号退款
            $result = $payment->refund($orderNo, $refundNo, $real_amount,$reamout);
            if($result['result_code']=='FAIL'){
                return ['code'=>-1050, 'msg'=>$result['err_code_des']];
            }
            //var_dump($result);die;
            //判断退款是否成功
            if($result['result_code']=='SUCCESS'&&$result['return_code']=='SUCCESS'){

                $rdata = array(
                    'oid' => session('oid'),
                    'uid' => $jine['id'],
                    'types' => 1,
                    'order_no' => $jine['order_no'],
                    'refund_no' => $refundNo,
                    'transaction_id' => $result['transaction_id'],
                    'refund_time' => time(),
                );
                Db::name('refund')->insert($rdata);
                $ldata = array(
                    'id' => $id,
                    'remarks' => "已退款".$reamout.'元',
                );
                $ok = Db::name('leaseorder')->update($ldata);
                Db::name('rechargeorder')->where('id',$jine['id'])->setField('refundbalance', input('amount'));
                if($ok !==false){
                    $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="refunds"; $uid=session('id'); $querystring = '退款金额'.round(input('amount'),2);$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    return ['code'=>0, 'msg'=>'退款成功!'];
                }else{
                    return ['code'=>-1050, 'msg'=>'退款失败!'];
                }

            }


        }else{
            $id = Request::instance()->get('id','','number_int');
            if(!empty($id)){
                $ret = Db::name('leaseorder')->where('id',$id)->find();
                $jine = Db::name('rechargeorder')->where(['oid'=>session('oid'),'uid'=>$ret['uid'],'pay_status'=>1,'deposit'=>array('eq',''),'balance'=>array('neq','')])->where('balance','>','0')->order('create_time asc')->find();
                //var_dump($jine);die;
                if($jine){
                    $this->assign('v',$jine);
                    return view('../application/publicview/orders/refunds.html');
                }else{
                    die('非法操作!');
                }

            }else{
                die('非法操作!');
            }

        }
    }

    //客户金额手动设置
    public function change(){
        if ( Request::instance()->isPost() ) {
            $data = input('post.');
            //var_dump($data);die;
            $cdata = array(
                'id' => $data['id'],
                'balance' => $data['zz'],
            );
            if($data['fuhao']=='+'){
                $add = '手动添加用户余额';
            }else{
                $add = '手动减去用户余额';
            }
            $ret = Db::name('user')->update($cdata);
            $bdata = array(
                'uid'=>$data['id'],
                'types' => 1,
                'amount' => $data['yue'],
                'name' => $add,
                'reason'=>'4',
                'orderid' =>'',
                'operatingtime'=>time(),
                'is_delete'=>1,
            );

            if($ret){
                Db::name('balance')->insert($bdata);
                $oid = session('oid');
                $m = 'ausagent';
                $c = 'orders';
                $action="deposit";
                $uid=session('id');
                $querystring = '为用户'.$data['id'].input('fuhao').'金额'.input('yue');
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);

                return ['code'=>0, 'msg'=>'更改金额成功!'];
            }else{
                return ['code'=>-1050, 'msg'=>'更改金额失败!'];
            }
        }else{
            $id = Request::instance()->get('id','','number_int');
            if(!empty($id)){
                $ret = Db::name('user')->where('id',$id)->find();
                $this->assign('v',$ret);
                return view('../application/publicview/orders/change.html');
            }
        }
    }
    //客户押金手动退款
    public function deposit(){
        if ( Request::instance()->isPost() ) {
            $id = (int)input('id');
            if(!$id){
                die('操作错误!');
            }
            $user = Db::name('user')->where('id',$id)->field('id,balance,deposit')->find();
            //var_dump($user);die;
            $Leaseorder = Db::name('leaseorder')->where('oid',session('oid'))->where('uid',$user['id'])-> where('status','neq',2)-> count();
            if(!$Leaseorder){
                $order = Db::name('rechargeorder')
                    ->where('oid',session('oid'))
                    ->where('uid',$user['id'])
                    ->where('deposit','>',0)
                    ->where('pay_status',1)
                    ->where('refunddeposit',0)
                    ->find();
                if(!$order){
                    return ['code'=>-1050, 'msg'=>'没有查到充值记录!'];
                }
                //var_dump($order);die;
                //var_dump($order);die;
                $app = $this ->initialize();
                $payment = $app->payment;
                $refundNo = '401' . date('ymdHis') . rand(1000, 9999);
                $real_amount = round($order['real_amount'],2)*100;
                $reamout = round($order['deposit'],2)*100;
                $orderNo = $order['order_no'];

                $result = $payment->refund($orderNo,$refundNo,$real_amount,$reamout,$order['oid']);//退款
                if($result['result_code']=='FAIL'){
                    return ['code'=>-1050, 'msg'=>$result['err_code_des']];
                }
                //var_dump($result);die;
                //判断退款是否成功
                if($result['result_code']=='SUCCESS'&&$result['return_code']=='SUCCESS'){

                    $return = array(
                        'oid' => session('oid'),
                        'uid' => $user['id'],
                        'types' => 1,
                        'order_no' => $order['order_no'],
                        'refund_no' => $refundNo,
                        'transaction_id' => $result['transaction_id'],
                        'refund_time' => time(),
                    );
                    Db::name('refund')->insert($return);
                    $recharge = Db::name('rechargeorder')->where('order_no',$order['order_no'])->update(['refunddeposit' => $order['deposit']]);
                    if(!$recharge){
                        //$res['info'] = '订单信息更新失败！';
                        return ['code'=>-1050, 'msg'=>'订单信息更新失败!'];
                    }
                    $updateuser = Db::name('user')->where('id',$user['id'])->setDec('deposit', $order['deposit']);
                    if(!$updateuser){
                        //$res['info']? $res['info'].= '用户信息更新失败！': $res['info']= '用户信息更新失败！';
                        return ['code'=>-1050, 'msg'=>'用户信息更新失败！'];
                    }else{
                        $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="deposit"; $uid=session('id'); $querystring = '押金退款'.$orderNo;$ip = get_ip();$os = get_os();
                        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                        return ['code'=>0, 'msg'=>'退款成功!'];
                    }
                }else{
                    return ['code'=>-1050, 'msg'=>'退款失败!'];
                }

            }else{
                return ['code'=>-1050, 'msg'=>'有订单未处理!'];
            }
            //var_dump($result);die;
        }else{
            die('非法操作!');
        }
    }

    public function rebalance(){
        if ( Request::instance()->isPost() ) {
            $data = input('post.');
            $refunds = $data['refunds'];
            $ids  = input('post.ids/a',[]);
            $count = Db::name('rechargeorder')
                ->where(['uid'=>$data['id'],'is_delete'=>1,'pay_status'=>1])
                ->where('balance','>',0)
                ->where('refundbalance','exp','< (balance)')
                ->count();
            if(!$count){
                return ['code'=>-1050, 'msg'=>'还没有充值记录!'];
            }
            $refundbalance = Db::name('rechargeorder')
                ->where(['uid'=>$data['id'],'is_delete'=>1,'pay_status'=>1])
                ->where('balance','>',0)
                ->where('refundbalance','exp','< (balance)')
                ->sum('refundbalance');
            $balance = Db::name('rechargeorder')
                ->where(['uid'=>$data['id'],'is_delete'=>1,'pay_status'=>1])
                ->where('balance','>',0)
                ->where('refundbalance','exp','< (balance)')
                ->sum('balance');
            $sum = $balance - $refundbalance;
            //var_dump($sum);die;
            if($data['refunds'] > $sum){
                return ['code'=>-1051, 'msg'=>'退款金额不能超过客户实际订单支付的总金额!'];
            }
            if($data['refunds']<=0){
                return ['code'=>-1052, 'msg'=>'退款金额不能为0!'];
            }
            $app = $this ->initialize();
            $payment = $app->payment;

            $ret = Db::name('rechargeorder')
                ->where(['uid'=>$data['id'],'is_delete'=>1,'pay_status'=>1])
                ->where('balance','>',0)
                ->where('refundbalance','exp','< (balance)')
                ->order('create_time desc')
                ->select();
            foreach ($ret as $k => $v) {
                //echo $v['uid'];die;
                $balance = $v['balance']- $v['refundbalance'];

                $refundNo = '401' . date('ymdHis') . rand(1000, 9999);
                $real_amount = round($v['real_amount'],2)*100;
                $reamout = round($balance,2)*100;
                $orderNo = $v['order_no'];

                if($refunds <= $balance){

                    $reamout = $refunds*100;

                }else{
                    $reamout = round($balance,2)*100;

                }


                $result = $payment->refund($orderNo,$refundNo,$real_amount,$reamout,$v['oid']);//退款

                if($result['result_code']=='SUCCESS'&&$result['return_code']=='SUCCESS'){
                    $reamout = $reamout/100;
                    $return = array(
                        'oid' => session('oid'),
                        'uid' => $v['uid'],
                        'types' => 2,
                        'fee' => $reamout,
                        'order_no' => $v['order_no'],
                        'refund_no' => $refundNo,
                        'transaction_id' => $result['transaction_id'],
                        'refund_time' => time(),
                    );
                    Db::name('refund')->insert($return);
                    $recharge = Db::name('rechargeorder')->where('order_no',$v['order_no'])->setInc('refundbalance',$reamout);

                    if(!$recharge){

                        //$res['info'] = '订单信息更新失败！';
                        return ['code'=>-1053, 'msg'=>'订单信息更新失败!'];
                    }
                    $updateuser = Db::name('user')->where('id',$v['uid'])->setDec('balance', $reamout);
                    if(!$updateuser){

                        //$res['info']? $res['info'].= '用户信息更新失败！': $res['info']= '用户信息更新失败！';
                        return ['code'=>-1054, 'msg'=>'用户信息更新失败！'];
                    }else{
                        $oid = session('oid');$m = 'ausagent'; $c = 'orders'; $action="rebalance"; $uid=session('id'); $querystring = '退款余额订单单号为:'.$orderNo.',退款了'.$balance.'元';$ip = get_ip();$os = get_os();
                        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);

                    }
                }else{
                    if(isset($result['err_code_des'])){
                        $msg = $result['err_code_des'];
                    }else{
                        $msg = $result['return_msg'];
                    }
                    return ['code'=>-1055, 'msg'=>$msg];

                }
                if($refunds > $balance){

                    $refunds = $refunds - $reamout;

                }else {

                    return ['code'=>0, 'msg'=>'退款成功!！'];

                }
            }
            //var_dump($balance);die;

            //var_dump($order);die;
        }else{
            die('非法操作!');
        }
    }
}